package com.ckzp.jfinal.weixin.impl;

import com.alibaba.fastjson.JSON;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.util.DateUtil;
import com.ckzp.jfinal.system.model.SysUser;
import com.ckzp.jfinal.weixin.model.WxMember;
import com.ckzp.weixin.service.MessageAction;
import com.ckzp.weixin.service.ServiceRequest;
import com.ckzp.weixin.service.ServiceResponse;
import com.ckzp.weixin.service.response.TextResponse;

import java.util.Date;

/**
 * Created by 51594 on 2023/4/11.
 */
public class EventScanAction implements MessageAction {
    /**
     * @param request
     * @return
     */
    public ServiceResponse doAction(ServiceRequest request) {
        if (request != null) {
            String wx_openid = request.getFromUserName();
            Jmode jmode = JSON.parseObject(request.getEventKey(), Jmode.class);
            TextResponse response = TextResponse.init(request);
            if ("web_login".equals(jmode.getStr("type"))) {
                String qr_uuid = jmode.getStr("qr_uuid");
                WxMember member = WxMember.dao.findFirst("select * from wx_member where wx_openid=?", wx_openid);
                if (member == null) {
                    Date create_date = new Date();
                    member = new WxMember().set("wx_openid", wx_openid).set("create_date", create_date).set("create_dateint", DateUtil.getYYYYMMDD(create_date));
                    member.save();
                }
                member.set("qr_uuid", qr_uuid).update();
                if (member.mod.getInt("emp_id", 0) == 0) {
                    response.setContent("您未绑定帐号");
                } else {
                    response.setContent("扫码登陆成功");
                }
            } else if ("web_bind".equals(jmode.getStr("type"))) {
                int emp_id = jmode.getInt("emp_id");
                String wx_uuid = jmode.getStr("wx_uuid");
                WxMember member = WxMember.dao.findFirst("select * from wx_member where wx_openid=?", wx_openid);
                SysUser user = SysUser.dao.findById(emp_id);
                if (member == null) {
                    Date create_date = new Date();
                    member = new WxMember().set("wx_openid", wx_openid).set("create_date", create_date).set("create_dateint", DateUtil.getYYYYMMDD(create_date));
                    member.save();
                }
                if (member != null && user != null) {
                    user.set("wx_openid", wx_openid).set("wx_uuid", wx_uuid).update();
                    member.set("emp_id", emp_id).update();
                    response.setContent("您已成功绑定微信帐户");
                } else {
                    response.setContent("绑定微信帐户失败");
                }
            } else {
                response.setContent(request.getEventKey() + "---" + jmode.toJson());
            }
            return response;
        }
        return null;
    }
}
